<template>
  <div class="command-center" :class="{ 'fullscreen-mode': isFullscreen }">
    <mapControl
      ref="mapControlRef"
      @drone-click="handleDroneClick"
      @tool-click="toolClick"
    />
    <div class="command-center-content" v-if="activePanel">
      <FigurePanel
        v-if="activePanel === 'figure'"
        :total-drones="totalDrones"
        :active-drones="activeDrones"
        :active-tasks="activeTasks"
        :anomaly-count="anomalyCount"
        @close="activePanel = null"
      />
      <TaskMonitorPanel
        v-else-if="activePanel === 'taskmonitor'"
        :task-list="taskList"
        :get-status-type="getStatusType"
        :get-task-row-class-name="getTaskRowClassName"
        @row-click="handleTaskRowClick"
        @close="activePanel = null"
      />
    </div>
    <DroneDialog
      v-model="droneDialogVisible"
      :selected-drone="selectedDrone"
      :task="selectedTask"
      :drone-form="droneForm"
      :drone-modes="droneModes"
      :payload-options="payloadOptions"
      :lost-actions="lostActions"
      :manual-controls="manualControls"
      :manual-control-status="manualControlStatus"
      :manual-control-feedback="manualControlFeedback"
      :is-control-active="isControlActive"
      :get-status-type="getStatusType"
      :flight-dashboard-metrics="flightDashboardMetrics"
      :max-altitude="MAX_ALTITUDE"
      @control-click="handleManualControlClick"
      @submit="submitDroneParams"
    />
    
    <!-- <TaskDetailPanel
      v-if="taskDetailVisible && selectedTask"
      :task="selectedTask"
      @close="taskDetailVisible = false"
    /> -->
  </div>
</template>

<script setup>
import {
  computed,
  inject,
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  watch,
} from "vue";
import { ElMessage } from "element-plus";
import { droneService } from "@/api";
import taskApi from "@/api/modules/task";
import DroneDialog from "./Command/DroneDialog.vue";
import FigurePanel from "./Command/FigurePanel.vue";
import TaskMonitorPanel from "./Command/TaskMonitorPanel.vue";
// import TaskDetailPanel from "./Command/TaskDetailPanel.vue";
import mapControl from "./Command/mapControl.vue";

const activePanel = ref(null);
const mapControlRef = ref(null);
const selectedTask = ref(null);
const selectedDrone = ref(null);
const droneDialogVisible = ref(false);
const taskDetailVisible = ref(false);
const isFullscreen = ref(false);
const MAX_ALTITUDE = 500;
const MAX_PITCH = 90;
const MAX_TOP_VIEW = 90;
const droneForm = reactive({
  altitude: 0,
  speed: 0,
  mode: "自动航线",
  payload: "高清摄像头",
  lostAction: "返航",
});
const droneModes = ["自动航线", "手动飞行", "巡逻模式"];
const payloadOptions = ["高清摄像头", "红外摄像头", "喊话器"];
const lostActions = ["返航", "降落", "悬停"];
const manualControls = [
  {
    id: "rotateLeft",
    label: "左转",
    keys: ["q"],
    displayKeys: "Q",
  },
  {
    id: "forward",
    label: "前进",
    keys: ["w", "arrowup"],
    displayKeys: "W / ↑",
  },
  {
    id: "rotateRight",
    label: "右转",
    keys: ["e"],
    displayKeys: "E",
  },
  {
    id: "ascend",
    label: "上升",
    keys: ["r", "pageup"],
    displayKeys: "R / PgUp",
  },
  {
    id: "left",
    label: "左移",
    keys: ["a", "arrowleft"],
    displayKeys: "A / ←",
  },
  {
    id: "backward",
    label: "后退",
    keys: ["s", "arrowdown"],
    displayKeys: "S / ↓",
  },
  {
    id: "right",
    label: "右移",
    keys: ["d", "arrowright"],
    displayKeys: "D / →",
  },
  {
    id: "descend",
    label: "下降",
    keys: ["f", "pagedown"],
    displayKeys: "F / PgDn",
  },
];
const manualControlsById = new Map();
const manualControlKeyMap = new Map();
manualControls.forEach((control) => {
  manualControlsById.set(control.id, control);
  control.keys.forEach((key) => {
    manualControlKeyMap.set(String(key).toLowerCase(), control);
  });
});
const manualControlActivation = new Map(
  manualControls.map((control) => [control.id, { keyboard: 0, button: 0 }])
);
const manualControlKeyState = new Map();
const activeControlIds = ref([]);
const lastManualCommand = ref("");
const lastManualSource = ref("");
const SOURCE_LABEL = {
  keyboard: "键盘",
  button: "界面",
};
const manualControlStatus = computed(() => {
  if (!activeControlIds.value.length) {
    return "当前未执行操作";
  }
  const labels = activeControlIds.value
    .map((id) => manualControlsById.get(id)?.label)
    .filter(Boolean);
  return labels.length ? `执行中：${labels.join("、")}` : "当前未执行操作";
});
const manualControlFeedback = computed(() => {
  if (!lastManualCommand.value) {
    return "尚未触发手动指令";
  }
  return `最近指令：${lastManualCommand.value}（${lastManualSource.value}）`;
});
const isControlActive = (controlId) =>
  activeControlIds.value.includes(controlId);
const updateManualControlState = (controlId) => {
  const state = manualControlActivation.get(controlId);
  if (!state) return;
  const active = (state.keyboard ?? 0) > 0 || (state.button ?? 0) > 0;
  const idx = activeControlIds.value.indexOf(controlId);
  if (active && idx === -1) {
    activeControlIds.value.push(controlId);
  } else if (!active && idx !== -1) {
    activeControlIds.value.splice(idx, 1);
  }
};
const setManualFeedback = (control, source) => {
  lastManualCommand.value = control.label;
  lastManualSource.value = SOURCE_LABEL[source] || source;
};
const activateControl = (controlId, source) => {
  const state = manualControlActivation.get(controlId);
  if (!state) return;
  state[source] = (state[source] || 0) + 1;
  updateManualControlState(controlId);
  const control = manualControlsById.get(controlId);
  if (control) {
    setManualFeedback(control, source);
  }
};
const deactivateControl = (controlId, source) => {
  const state = manualControlActivation.get(controlId);
  if (!state) return;
  if (state[source] > 0) {
    state[source] -= 1;
    updateManualControlState(controlId);
  }
};
const handleManualKeyDown = (event) => {
  const key = event.key?.toLowerCase?.();
  if (!key) return;
  const control = manualControlKeyMap.get(key);
  if (!control) return;
  const target = event.target;
  const tagName = target?.tagName?.toLowerCase?.();
  if (tagName && ["input", "textarea", "select"].includes(tagName)) {
    return;
  }
  if (target?.isContentEditable) return;
  event.preventDefault();
  let keySet = manualControlKeyState.get(control.id);
  if (!keySet) {
    keySet = new Set();
    manualControlKeyState.set(control.id, keySet);
  }
  if (keySet.has(key)) return;
  keySet.add(key);
  activateControl(control.id, "keyboard");
};
const handleManualKeyUp = (event) => {
  const key = event.key?.toLowerCase?.();
  if (!key) return;
  const control = manualControlKeyMap.get(key);
  if (!control) return;
  event.preventDefault();
  const keySet = manualControlKeyState.get(control.id);
  if (!keySet || !keySet.has(key)) return;
  keySet.delete(key);
  if (!keySet.size) {
    manualControlKeyState.delete(control.id);
    deactivateControl(control.id, "keyboard");
  }
};
const handleManualControlClick = (controlId) => {
  if (!manualControlsById.has(controlId)) return;
  activateControl(controlId, "button");
  setTimeout(() => {
    deactivateControl(controlId, "button");
  }, 220);
};

const flightDashboardMetrics = computed(() => {
  const drone = selectedDrone.value;

  const pickNumber = (...values) => {
    for (const value of values) {
      if (value === undefined || value === null) continue;
      const numeric = Number(value);
      if (Number.isFinite(numeric)) {
        return numeric;
      }
    }
    return null;
  };

  const altitudeValue = Math.max(
    0,
    Math.round(droneForm.altitude || drone?.altitude || 0)
  );
  const speedValue = Math.max(
    0,
    Math.round(droneForm.speed || drone?.speed || 0)
  );
  const rawHeading = Number.isFinite(drone?.heading) ? drone.heading : 0;
  const headingValue = ((Math.round(rawHeading) % 360) + 360) % 360;
  const pitchValue = Number.isFinite(drone?.pitch)
    ? Math.round(drone.pitch)
    : 0;
  const rollValue = Number.isFinite(drone?.roll)
    ? Math.round(drone.roll)
    : Number.isFinite(drone?.bankAngle)
    ? Math.round(drone.bankAngle)
    : 0;
  const topViewValue = Number.isFinite(drone?.topViewAngle)
    ? Math.round(drone.topViewAngle)
    : pitchValue;
  const ascentRateValue =
    pickNumber(drone?.ascentRate, drone?.verticalSpeed, drone?.climbRate) || 0;
  const airSpeedValue =
    pickNumber(
      drone?.airSpeed,
      drone?.airspeed,
      drone?.speedAir,
      drone?.speed,
      speedValue
    ) || 0;
  const groundSpeedValue =
    pickNumber(drone?.groundSpeed, drone?.ground_speed, drone?.speed) ||
    speedValue;
  const windSpeedValue = pickNumber(drone?.windSpeed, drone?.wind_speed) || 0;
  const flightTimeValue = pickNumber(
    drone?.flightTime,
    drone?.missionDuration,
    drone?.elapsedTime
  );
  const seaLevelAltitudeValue = pickNumber(
    drone?.seaLevelAltitude,
    drone?.altitudeMSL,
    drone?.mslAltitude
  );
  const distanceValue = pickNumber(
    drone?.distance,
    drone?.distanceTravelled,
    drone?.missionDistance
  );

  const altitudePercent = Math.min(
    100,
    Math.max(0, Math.round((altitudeValue / MAX_ALTITUDE) * 100))
  );
  const pitchPercent = Math.min(
    100,
    Math.max(0, Math.round(((pitchValue + MAX_PITCH) / (MAX_PITCH * 2)) * 100))
  );
  const topViewPercent = Math.min(
    100,
    Math.max(
      0,
      Math.round(((topViewValue + MAX_TOP_VIEW) / (MAX_TOP_VIEW * 2)) * 100)
    )
  );

  return {
    altitude: altitudeValue,
    altitudePercent,
    speed: speedValue,
    heading: headingValue,
    pitch: pitchValue,
    pitchPercent,
    roll: rollValue,
    topViewAngle: topViewValue,
    topViewPercent,
    ascentRate: ascentRateValue,
    airSpeed: airSpeedValue,
    groundSpeed: groundSpeedValue,
    windSpeed: windSpeedValue,
    flightTime: flightTimeValue,
    seaLevelAltitude: seaLevelAltitudeValue,
    distance: distanceValue,
    maxAltitude: MAX_ALTITUDE,
  };
});

const toolClick = (toolId) => {
  if (!toolId) {
    activePanel.value = null;
    return;
  }
  if (toolId === "figure" || toolId === "taskmonitor") {
    activePanel.value = toolId;
  } else {
    activePanel.value = null;
  }
  if (activePanel.value !== "taskmonitor") {
    droneDialogVisible.value = false;
  }
};
// 统计数据
const totalDrones = ref(0);
const activeDrones = ref(0);
const activeTasks = ref(0);
const anomalyCount = ref(0);

// 从后端获取无人机统计数据
const fetchDroneStats = async () => {
  try {
    const response = await droneService.getDrones();
    // console.log('drones', response.data.items);
    const drones = response.data.items;
    totalDrones.value = drones.length;
    activeDrones.value = drones.filter(
      (d) => d.status === "available" || d.status === "busy"
    ).length;
    anomalyCount.value = drones.filter(
      (d) => d.status === "broken" || d.status === "maintenance"
    ).length;
    activeTasks.value = drones.filter((d) => d.status === "busy").length;
  } catch (error) {
    console.error("获取无人机统计数据失败:", error);
    ElMessage.error("获取无人机统计数据失败");
  }
};

// 从后端获取任务列表
const fetchTaskList = async () => {
  try {
    const response = await taskApi.getTasks();
    // 正确处理后端返回的数据结构
    // 通常API响应会包含在data字段中
    const responseData = response.data || response;
    // 获取任务列表数据，兼容不同的数据结构
    const tasks =
      responseData.items || responseData.results || responseData || [];
    console.log("获取到的任务列表:", tasks);
    // 转换任务数据格式以适配前端组件需求
    taskList.value = tasks.map((task) => ({
      id: task.id,
      name: task.name,
      droneId: task.drone_id || task.droneId || "",
      status: mapTaskStatus(task.status),
      progress: task.progress || 0,
      flightPath: task.flight_path || task.flightPath || [],
      // 添加更多可能需要的字段
      priority: task.priority || "medium",
      startTime: task.start_time || task.startTime || null,
      endTime: task.end_time || task.endTime || null,
      createTime: task.create_time || task.createTime || null,
      description: task.description || "",
    }));

    // 默认选中第一个任务
    nextTick(() => {
      if (
        taskList.value.length > 0 &&
        (!selectedTask.value ||
          !taskList.value.find((t) => t.id === selectedTask.value.id))
      ) {
        handleTaskRowClick(taskList.value[0]);
      }
    });
  } catch (error) {
    console.error("获取任务列表失败:", error);
    ElMessage.error("获取任务列表失败");
    // 出错时可以使用一些模拟数据作为备选
    taskList.value = [];
  }
};

// 映射任务状态
const mapTaskStatus = (status) => {
  const statusMap = {
    pending: "待执行",
    running: "执行中",
    completed: "已完成",
    failed: "已失败",
  };
  return statusMap[status] || status;
};

// 任务列表
const taskList = ref([]);

// 无人机数据，从后端获取
const drones = ref([]);

// 从后端获取无人机详细数据
const fetchDrones = async () => {
  try {
    const response = await droneService.getDrones();
    // 正确处理后端返回的数据结构
    const responseData = response.data || response;
    const droneData =
      responseData.items || responseData.results || responseData || [];
    console.log("获取到的无人机数据:", droneData);

    // 转换无人机数据格式以适配前端组件需求
    drones.value = droneData.map((drone) => {
      // 映射飞行模式
      const modeMap = {
        auto: "自动航线",
        manual: "手动飞行",
        hover: "悬停",
        return: "返航",
      };

      return {
        id: drone.id,
        name: drone.name || `无人机${drone.id}`,
        status: drone.status || "available", // 使用后端原始状态值
        latitude: drone.latitude || 34.3416,
        longitude: drone.longitude || 108.9398,
        altitude: drone.altitude || 0,
        speed: drone.speed || 0,
        battery: drone.battery_percentage || drone.battery || 0,
        currentFrame:
          drone.camera_image ||
          `https://picsum.photos/400/225?drone=${drone.id}`,
        taskProgress: drone.task_progress || 0,
        streamUrl:
          drone.stream_url ||
          "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4",
        mode: modeMap[drone.flight_mode] || drone.flight_mode || "自动航线",
        payload: drone.payload || "高清摄像头",
        lostAction: drone.lost_action || "返航",
        heading: drone.heading || 0,
        pitch: drone.pitch || 0,
        topViewAngle: drone.camera_angle || 45,
        // 保留后端原始数据，便于后续使用
        originalData: drone,
      };
    });
  } catch (error) {
    console.error("获取无人机数据失败:", error);
    ElMessage.error("获取无人机数据失败");
    // 如果获取失败，可以使用默认的模拟数据
    drones.value = [];
  }
};

const fillDroneForm = (drone) => {
  if (!drone) return;
  droneForm.altitude = Math.round(drone.altitude || 0);
  droneForm.speed = Math.round(drone.speed || 0);
  droneForm.mode = drone.mode || "自动航线";
  droneForm.payload = drone.payload || "高清摄像头";
  droneForm.lostAction = drone.lostAction || "返航";
};

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    // 后端无人机状态映射
    available: "success", // 可用
    busy: "primary", // 忙碌
    maintenance: "warning", // 维护
    broken: "danger", // 故障
  };
  return statusMap[status] || "warning";
};

const getTaskRowClassName = ({ row }) => {
  if (selectedTask.value && row.id === selectedTask.value.id) {
    return "selected-task-row";
  }
  return "";
};

const handleTaskRowClick = async (row) => {
  if (!row) return;
  
  try {
    // 先设置基本信息
    selectedTask.value = row;
    
    // 获取任务详情
    const taskDetailResponse = await taskApi.getTaskDetail(row.id);
    const taskDetail = taskDetailResponse.data || taskDetailResponse;
    
    console.log('任务详情:', taskDetail);
    
    // 更新selectedTask，包含完整的任务详情
    selectedTask.value = {
      ...row,
      // 合并详细信息
      task_routes: taskDetail.task_routes || [],
      task_drones: taskDetail.task_drones || [],
      detection_model_ids: taskDetail.detection_model_ids || [],
      description: taskDetail.description || '',
      priority: taskDetail.priority || 'medium',
      start_time: taskDetail.start_time || taskDetail.startTime,
      end_time: taskDetail.end_time || taskDetail.endTime,
      execute_type: taskDetail.execute_type,
      scheduled_time: taskDetail.scheduled_time,
      responsible_person: taskDetail.responsible_person || taskDetail.responsiblePerson
    };
    
    // 查找关联的无人机
    if (taskDetail.task_drones && taskDetail.task_drones.length > 0) {
      // 优先使用主用无人机
      const mainDrone = taskDetail.task_drones.find(td => td.is_primary || td.isPrimary);
      const droneIdToFind = mainDrone?.drone_id || mainDrone?.droneId || row.droneId;
      
      const drone = drones.value.find((item) => item.id === droneIdToFind);
      if (drone) {
        selectedDrone.value = drone;
        fillDroneForm(drone);
      }
    } else if (row.droneId) {
      const drone = drones.value.find((item) => item.id === row.droneId);
      if (drone) {
        selectedDrone.value = drone;
        fillDroneForm(drone);
      }
    }
    
    // 构建完整的飞行路径
    let flightPath = row.flightPath || [];
    let startPoint = null;
    
    if (taskDetail.task_routes && taskDetail.task_routes.length > 0) {
      // 从任务航线中提取坐标点
      const routePoints = [];
      taskDetail.task_routes.forEach(taskRoute => {
        if (taskRoute.route && taskRoute.route.waypoints) {
          taskRoute.route.waypoints.forEach(waypoint => {
            if (waypoint.lat && waypoint.lng) {
              routePoints.push({
                lat: waypoint.lat,
                lng: waypoint.lng,
                alt: waypoint.alt || 0
              });
            }
          });
        }
      });
      if (routePoints.length > 0) {
        flightPath = routePoints;
        // 获取航线起点
        startPoint = flightPath[0];
      }
    }
    
    // 检查任务是否未开始（状态为pending或类似状态）
    const isTaskNotStarted = row.status === 'pending' || row.status === 'scheduled' || !row.start_time;
    
    // 如果任务未开始且有起点坐标，并且有选中的无人机，则将无人机坐标设置为起点
    if (isTaskNotStarted && startPoint && selectedDrone.value) {
      console.log('任务未开始，将无人机坐标设置为航线起点:', startPoint);
      // 创建无人机位置的副本，避免直接修改原始数据
      const updatedDrone = {
        ...selectedDrone.value,
        lat: startPoint.lat,
        lng: startPoint.lng,
        latitude: startPoint.lat,
        longitude: startPoint.lng,
        altitude: startPoint.alt || 0
      };
      
      // 更新选中的无人机位置
      selectedDrone.value = updatedDrone;
      
      // 更新无人机数据列表中的位置
      const droneIndex = drones.value.findIndex(d => d.id === selectedDrone.value.id);
      if (droneIndex !== -1) {
        drones.value[droneIndex] = updatedDrone;
      }
      
      ElMessage.info('已将无人机位置设置为航线起点');
    }
    
    // 在地图上显示任务
    if (mapControlRef.value?.showTaskOnMap) {
      mapControlRef.value.showTaskOnMap({
        taskName: row.name,
        flightPath: flightPath,
        drone: selectedDrone.value,
        taskDetail: selectedTask.value
      });
    }
    
    // 显示任务详情面板
    taskDetailVisible.value = true;
    ElMessage.success(`已加载任务详情：${row.name}`);
    
  } catch (error) {
    console.error('获取任务详情失败:', error);
    ElMessage.error('获取任务详情失败');
  }
};

const handleDroneClick = (drone) => {
  if (!drone) return;
  selectedDrone.value = drone;
  fillDroneForm(drone);
  activePanel.value = null;
  mapControlRef.value?.resetActiveTool?.();
  droneDialogVisible.value = true;
};

watch(droneDialogVisible, (visible) => {
  if (!visible) {
    activePanel.value = "taskmonitor";
    nextTick(() => {
      mapControlRef.value?.externallyActivateTool?.("taskmonitor");
    });
  }
});

const submitDroneParams = () => {
  if (selectedDrone.value) {
    selectedDrone.value.altitude = droneForm.altitude;
    selectedDrone.value.speed = droneForm.speed;
    selectedDrone.value.mode = droneForm.mode;
    selectedDrone.value.payload = droneForm.payload;
    selectedDrone.value.lostAction = droneForm.lostAction;
    ElMessage.success("无人机参数更新成功");
    if (mapControlRef.value?.showTaskOnMap && selectedTask.value) {
      mapControlRef.value.showTaskOnMap({
        taskName: selectedTask.value.name,
        flightPath: selectedTask.value.flightPath || [],
        drone: selectedDrone.value,
      });
    }
  }
  droneDialogVisible.value = false;
};

onMounted(() => {
  window.addEventListener("keydown", handleManualKeyDown);
  window.addEventListener("keyup", handleManualKeyUp);
  // 获取无人机统计数据
  fetchDroneStats();
  // 获取无人机详细数据
  fetchDrones();
  // 获取任务列表
  fetchTaskList();
  // 启动实时数据更新
  // startRealTimeUpdate();
});

onBeforeUnmount(() => {
  window.removeEventListener("keydown", handleManualKeyDown);
  window.removeEventListener("keyup", handleManualKeyUp);
  manualControlKeyState.clear();
  manualControlActivation.forEach((state) => {
    state.keyboard = 0;
    state.button = 0;
  });
  activeControlIds.value = [];
  // 清除实时更新定时器
  clearRealTimeUpdate();
});

// 已在script setup中定义，自动暴露给模板
let mapInterval;
let updateCounter = 0;

// 实时数据更新
const startRealTimeUpdate = () => {
  mapInterval = setInterval(async () => {
    updateCounter++;

    if (updateCounter % 6 === 0) {
      // 每30秒重新获取一次完整数据 (5秒/次 * 6次 = 30秒)
      await fetchDrones();
      await fetchDroneStats();
      await fetchTaskList();
    } else {
      // 其他时间只更新统计数据和任务列表
      await fetchDroneStats();
      await fetchTaskList();

      // 为了更好的用户体验，可以对现有无人机数据做一些动态更新
      // 这些更新不会覆盖从后端获取的核心数据
      if (drones.value.length > 0) {
        drones.value.forEach((drone) => {
          // 轻微调整位置，模拟实时移动
          if (drone.status === "正常" || drone.status === "执行任务") {
            drone.latitude += (Math.random() - 0.5) * 0.001;
            drone.longitude += (Math.random() - 0.5) * 0.001;

            // 电池缓慢消耗
            drone.battery = Math.max(0, drone.battery - Math.random() * 0.5);

            // 速度轻微变化
            drone.speed = Math.max(
              0,
              Math.min(20, drone.speed + (Math.random() - 0.5) * 2)
            );

            // 更新任务进度
            if (drone.taskProgress < 100) {
              drone.taskProgress = Math.min(
                100,
                drone.taskProgress + Math.random() * 2
              );
            }
          }
        });
      }
    }

    // 更新任务进度
    if (taskList.value.length > 0) {
      taskList.value.forEach((task) => {
        if (task.status === "执行中") {
          task.progress = Math.min(100, task.progress + Math.random() * 3);
          if (task.progress >= 100) {
            task.status = "已完成";
          }
        }
      });
    }
  }, 5000); // 5秒更新一次
};

// 清除定时器的函数
const clearRealTimeUpdate = () => {
  if (mapInterval) {
    clearInterval(mapInterval);
    mapInterval = null;
    console.log("实时更新定时器已清除");
  }
};

// 监听activePanel变化，当面板关闭时清除定时器
watch(activePanel, (newValue) => {
  if (newValue === null) {
    clearRealTimeUpdate();
  } else if (newValue === "figure" || newValue === "taskmonitor") {
    // 当面板打开且定时器不存在时，启动定时器
    if (!mapInterval) {
      // startRealTimeUpdate();
    }
  }
});
</script>

<style scoped>
.command-center {
  height: 100%;
  position: relative;
}

/* 全屏模式下的样式调整 */
.command-center.fullscreen-mode {
  background-color: #000;
}

/* 全屏模式下确保地图控件占满整个屏幕 */
.command-center.fullscreen-mode .map-container {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  z-index: 9999;
}

.command-center-content {
  position: absolute;
  top: 12px;
  right: 45px;
  z-index: 900;
  display: flex;
  flex-direction: column;
  max-width: 360px;
}

.command-center-content > * {
  position: relative;
  z-index: 1;
}

:deep(.info-panel),
:deep(.monitor-panel) {
  width: 320px;
  background: rgba(15, 23, 42, 0.88);
  border-radius: 16px;
  padding: 14px;
  overflow-y: auto;
  height: calc(100vh - 200px);
  color: #e5e7eb;
  border: 1px solid rgba(148, 163, 184, 0.12);
  box-shadow: 0 20px 40px rgba(15, 23, 42, 0.45);
  backdrop-filter: blur(12px);
}

:deep(.section-header) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}

:deep(.section-header h3) {
  margin: 0;
  font-size: 18px;
  color: #f3f4f6;
  letter-spacing: 0.5px;
}

:deep(.stats-grid) {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

:deep(.stat-item) {
  text-align: center;
  padding: 10px 16px;
  background: linear-gradient(
    145deg,
    rgba(30, 41, 59, 0.75),
    rgba(15, 23, 42, 0.65)
  );
  border-radius: 12px;
  border: 1px solid rgba(148, 163, 184, 0.22);
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
}

:deep(.stat-number) {
  display: block;
  font-size: 32px;
  font-weight: bold;
  color: #38bdf8;
}

:deep(.stat-label) {
  display: block;
  font-size: 14px;
  color: #cbd5f5;
  margin-top: 10px;
  letter-spacing: 0.2px;
}

:deep(.stats-collapsed) {
  padding: 20px;
  border-radius: 12px;
  border: 1px dashed rgba(148, 163, 184, 0.35);
  background: rgba(30, 41, 59, 0.4);
  color: #9ca3af;
  text-align: center;
  font-size: 14px;
}

:deep(.stats-toggle-enter-active),
:deep(.stats-toggle-leave-active) {
  transition: opacity 0.2s ease, transform 0.2s ease;
}

:deep(.stats-toggle-enter-from),
:deep(.stats-toggle-leave-to) {
  opacity: 0;
  transform: translateY(-6px);
}

:deep(.route-close) {
  border: none;
  background: transparent;
  color: #9ca3af;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
}

::deep(.route-close:hover) {
  color: #e5e7eb;
}

.map-container {
  flex: 1;
  background: rgba(15, 23, 42, 0.75);
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  border: 1px solid rgba(148, 163, 184, 0.15);
}

:deep(.el-table) {
  background: transparent;
  color: #e5e7eb;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: rgba(30, 41, 59, 0.65);
  --el-table-border-color: rgba(14, 33, 60, 0.18);
  height: 190px;
}

:deep(.el-table th),
:deep(.el-table td) {
  background: rgba(30, 41, 59, 0.5);
  border-bottom: 1px solid rgba(148, 163, 184, 0.12);
}

:deep(.el-table__body tr:hover > td) {
  background: rgba(59, 130, 246, 0.15) !important;
}

/* :deep(.el-tag) {
  background: rgba(59, 130, 246, 0.2);
  border-color: rgba(59, 130, 246, 0.35);
  color: #93c5fd;
} */

.map-controls {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.map-control-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.map-markers {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  gap: 40px;
}

.drone-marker {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s;
}

.drone-marker:hover {
  transform: scale(1.2);
}

.drone-info-popup {
  position: absolute;
  background-color: white;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  width: 300px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e6e6e6;
}

.popup-header h4 {
  margin: 0;
  font-size: 16px;
}

.close-icon {
  cursor: pointer;
  color: #999;
}

.close-icon:hover {
  color: #333;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-row .label {
  color: #666;
}

.info-row .value {
  font-weight: 500;
  color: #333;
}

.current-frame {
  margin-top: 16px;
}

.current-frame h5 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
}

.frame-img {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #e6e6e6;
}

.progress-container {
  margin: 12px 0;
}

.action-buttons {
  margin-top: 16px;
  display: flex;
  gap: 8px;
  justify-content: space-between;
}

:deep(.selected-task-row) {
  background-color: #303334 !important;
}

:deep(.el-table__body tr.current-row > td.el-table__cell) {
  background-color: rgb(44 58 73);
}
/* 全屏按钮样式 */
.fullscreen-btn {
  position: fixed;
  top: 12px;
  right: 10px;
  z-index: 1000;
  background: rgba(24, 144, 255, 0.9);
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.fullscreen-btn:hover {
  background: rgba(24, 144, 255, 1);
  transform: scale(1.1);
}

.fullscreen-btn:active {
  transform: scale(0.95);
}

/* 全屏模式下的样式调整 */
:fullscreen .command-center {
  height: 100vh;
  width: 100vw;
}

:fullscreen .fullscreen-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 2147483647; /* 最大z-index值 */
  background: rgba(24, 144, 255, 0.95);
}

/* 兼容不同浏览器的全屏伪类 */
:-webkit-full-screen .command-center {
  height: 100vh;
  width: 100vw;
}

:-moz-full-screen .command-center {
  height: 100vh;
  width: 100vw;
}

:-ms-fullscreen .command-center {
  height: 100vh;
  width: 100vw;
}
</style>
